/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sgt.supermarket.controller.sales;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sgt.supermarket.entity.Invoice;
import sgt.supermarket.entity.InvoiceItem;
import sgt.supermarket.entity.Product;
import sgt.supermarket.entity.ProductBlock;
import sgt.supermarket.entity.SaleProgram;
import sgt.supermarket.hibernatedao.HibernateDAOFactory;
import sgt.supermarket.util.ServletExtensions;

/**
 *
 * @author Administrator
 */
public class CreateInvoice extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateDAOFactory factory = new HibernateDAOFactory();
        Invoice invoice;
        if (request.getParameter("uid") == null) {
            invoice = new Invoice();
            invoice.setSalesperson(factory.getEmployeeDAO().getByUsername(request.getRemoteUser()));
            invoice.setCreatedDate(new Date());
            factory.getInvoiceDAO().save(invoice);
            factory.getInvoiceDAO().save(invoice);
            response.sendRedirect("createInvoice?uid=" + invoice.getAutoId());
            return;
        }
        invoice = factory.getInvoiceDAO().getById(ServletExtensions.getLongParam(request, "uid"));
        if (request.getMethod().equalsIgnoreCase("POST")) {
            if (request.getParameter("findCustomer") != null) {
                request.getSession().setAttribute("customerKey", request.getParameter("customerKey"));
                request.getSession().setAttribute("suggestedCustomers", factory.getCustomerDAO().getByKeyword(request.getParameter("customerKey")));
            } else if (request.getParameter("findProduct") != null) {
                request.getSession().setAttribute("productKey", request.getParameter("productKey"));
                request.getSession().setAttribute("suggestedProducts", factory.getProductDAO().getByKeyword(request.getParameter("productKey")));
            } else if (request.getParameter("selectCustomer") != null) {
                selectCustomer(request, invoice, factory);
            } else if (request.getParameter("insertProduct") != null) {
                insertProduct(request, invoice, factory);
            } else if (request.getParameter("updateQuantity") != null) {
                updateQuantity(request, invoice, factory);
            } else if (request.getParameter("removeItem") != null) {
                removeInvoiceItem(request, invoice, factory);
            } else if (request.getParameter("cancelInvoice") != null) {
                factory.getInvoiceDAO().delete(invoice);
                response.sendRedirect(request.getContextPath() + "/home/index");
                return;
            } else if (request.getParameter("saveInvoice") != null) {
                saveInvoice(invoice, factory);
                response.sendRedirect("printInvoice?uid=" + invoice.getAutoId());
                return;
            }
        }
        request.setAttribute("title", "Create invoice");
        request.setAttribute("invoice", invoice);
        request.getRequestDispatcher("/sales.createInvoice.tiles").forward(request, response);
    }

    private void saveInvoice(Invoice invoice, HibernateDAOFactory factory) {
        for (InvoiceItem item : invoice.getInvoiceItems()) {
            saveInvoiceItem(item, factory);
        }
        double discount = 0;
        List<SaleProgram> salePrograms = factory.getSaleProgramDAO().getByDateAndMinimumInvoiceTotal(invoice.getCreatedDate(), invoice.getTotalPrice());
        for (SaleProgram program : salePrograms) {
            discount += invoice.getTotalPrice() * program.getDiscountRate();
        }
        invoice.setDiscount(discount);
        factory.getInvoiceDAO().save(invoice);
    }

    private void saveInvoiceItem(InvoiceItem item, HibernateDAOFactory factory) {
        double diff = item.getQuantity();
        if (diff > 0) {
            List<ProductBlock> blocks = factory.getProductBlockDAO().getAvailablesByProductId(item.getProduct().getAutoId());
            int index = blocks.size() - 1;
            while (diff > 0) {
                ProductBlock block = blocks.get(index);
                double s;
                if (block.getAvailableUnits() >= diff) {
                    s = diff;
                    diff = 0;
                } else {
                    s = block.getAvailableUnits();
                    diff = diff - s;
                }
                block.setAvailableUnits(block.getAvailableUnits() - s);
            }
            factory.getProductBlockDAO().save(blocks.toArray(new ProductBlock[blocks.size()]));
        }
    }

    private void removeInvoiceItem(HttpServletRequest request, Invoice invoice, HibernateDAOFactory factory) {
        long invoiceItemId = ServletExtensions.getLongParam(request, "removeInvoiceItemId");
        for (InvoiceItem item : invoice.getInvoiceItems()) {
            if (item.getAutoId() == invoiceItemId) {
                invoice.removeInvoiceItem(item);
                break;
            }
        }
        factory.getInvoiceDAO().save(invoice);
    }

    private void updateQuantity(HttpServletRequest request, Invoice invoice, HibernateDAOFactory factory) {
        for (InvoiceItem item : invoice.getInvoiceItems()) {
            String quantityKey = String.format("iq_%d", item.getAutoId());
            item.setQuantity(ServletExtensions.getDoubleParam(request, quantityKey));
        }
        factory.getInvoiceDAO().save(invoice);
    }

    private void selectCustomer(HttpServletRequest request, Invoice invoice, HibernateDAOFactory factory) {
        invoice.setCustomer(factory.getCustomerDAO().getById(ServletExtensions.getLongParam(request, "customerId")));
        factory.getInvoiceDAO().save(invoice);
        request.getSession().removeAttribute("suggestedCustomers");
    }

    private void insertProduct(HttpServletRequest request, Invoice invoice, HibernateDAOFactory factory) {
        double quantity = ServletExtensions.getDoubleParam(request, "quantity");
        long productId = ServletExtensions.getLongParam(request, "productId");
        Product product = factory.getProductDAO().getById(productId);
        InvoiceItem oldItem = null;
        for (InvoiceItem item : invoice.getInvoiceItems()) {
            if (item.getProduct() == product) {
                oldItem = item;
                break;
            }
        }
        if (oldItem != null) {
            oldItem.setQuantity(oldItem.getQuantity() + quantity);
        } else {
            InvoiceItem invoiceItem = new InvoiceItem(product, quantity, product.getCurrentSellingPrice());
            invoice.addInvoiceItem(invoiceItem);
        }

        factory.getInvoiceDAO().save(invoice);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
